﻿//Copypasted from ProfessioanlBuddy

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Media;
using Styx.Common;

namespace PetBuddy
{
    public partial class svn
    {
        #region Variables

        public static int _revision { get { return int.Parse(revision) + 1; } }

        private static string logUrl = "http://code.google.com/p/petbuddy/source/detail?r=" + _revision;
        public static readonly string BotPath = Utilities.AssemblyDirectory + @"\Bots\PetBuddy";

        private static Regex _linkPattern = new Regex(@"<li><a href="".+"">(?<ln>.+(?:..))</a></li>",
                                                      RegexOptions.CultureInvariant);

        private static Regex _changelogPattern =
            new Regex(
                "<h4 style=\"margin-top:0\">Log message</h4>\r?\n?<pre class=\"wrap\" style=\"margin-left:1em\">(?<log>.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?)</pre>",
                RegexOptions.CultureInvariant);

        #endregion
        

        private static int GetRevision()
        {
            var client = new WebClient();
            var html = client.DownloadString(svnUrl);
            var pattern = new Regex(@" - Revision (?<rev>\d+):", RegexOptions.CultureInvariant);
            var match = pattern.Match(html);
            if (match.Success && match.Groups["rev"].Success)
                return int.Parse(match.Groups["rev"].Value);
            throw new Exception("Unable to check svn revision");
        }

        private static string GetChangeLog()
        {
            var client = new WebClient();
            var html = client.DownloadString(logUrl);
            var match = _changelogPattern.Match(html);
            if (match.Success && match.Groups["log"].Success)
                return RemoveXmlEscapes(match.Groups["log"].Value);
            return null;
        }

        private static string RemoveXmlEscapes(string xml)
        {
            return xml
                .Replace("&amp;", "&")
                .Replace("&lt;", "<")
                .Replace("&gt;", ">")
                .Replace("&quot;", "\"")
                .Replace("&apos;", "'");
        }

        private static void DownloadFilesFromSvn(WebClient client, string url)
        {
            var html = client.DownloadString(url);
            var results = _linkPattern.Matches(html);

            var matches = from match in results.OfType<Match>()
                          where match.Success && match.Groups["ln"].Success
                          select match;

            foreach (var match in matches)
            {
                var file = RemoveXmlEscapes(match.Groups["ln"].Value);
                var newUrl = url + file;

                if (newUrl[newUrl.Length - 1] == '/') // it's a directory...
                {
                    DownloadFilesFromSvn(client, newUrl);
                } else // its a file.
                {
                    string filePath, dirPath;

                    if (url.Length > svnUrl.Length)
                    {
                        var relativePath = url.Substring(svnUrl.Length);
                        dirPath = Path.Combine(BotPath, relativePath);
                        filePath = Path.Combine(dirPath, file);
                    } else
                    {
                        dirPath = Environment.CurrentDirectory;
                        filePath = Path.Combine(BotPath, file);
                    }

                    Logging.Write(Colors.LightGray, "Downloading {0}", file);

                    if (!Directory.Exists(dirPath))
                        Directory.CreateDirectory(dirPath);

                    client.DownloadFile(newUrl, filePath);
                }
            }
        }

        public static void CheckForUpdate()
        {
            try
            {
                PetBuddy.slog("Checking for new version");
                var remoteRev = GetRevision();

                if (PetBuddySettings.Instance.curRevision != remoteRev && _revision < remoteRev)
                {
                    PetBuddy.slog("A new version was found. Downloading Update");
                    DownloadFilesFromSvn(new WebClient(), svnUrl);
                    PetBuddy.slog("Download complete.");

                    PetBuddySettings.Instance.curRevision = remoteRev;

                    Logging.Write(Colors.DodgerBlue, "************* Change Log ****************");
                    Logging.Write(Colors.SkyBlue, GetChangeLog());
                    Logging.Write(Colors.DodgerBlue, "*****************************************");
                    Logging.Write(Colors.Red, "A new version of PetBuddy was installed. Please restart Honorbuddy");

                } else
                {
                    PetBuddy.slog("No updates found");
                }
            }
            catch (Exception ex)
            {
                PetBuddy.rlog(ex.ToString());
            }
        }

    }
}
